package cn.lili.modules.member.serviceimpl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.Extension;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.vo.ExtensionVO;
import cn.lili.modules.member.entity.vo.GradeVO;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.entity.vo.PartnerVO;
import cn.lili.modules.member.mapper.ExtensionMapper;
import cn.lili.modules.member.mapper.MemberMapper;
import cn.lili.modules.member.mapper.PartnerMapper;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.mapper.OrderMapper;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.system.entity.dos.Region;
import cn.lili.modules.system.mapper.RegionMapper;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.wallet.entity.dos.Recharge;
import cn.lili.modules.wallet.mapper.RechargeMapper;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ExtensionServiceImpl extends ServiceImpl<ExtensionMapper, Extension> implements EextensionService {

	private Logger log = LoggerFactory.getLogger(ExtensionServiceImpl.class);
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private RechargeMapper rechargeMapper;

	@Autowired
	private RegionMapper regionMapper;

	@Autowired
	private PartnerMapper partnerMapper;

	@Autowired
	private MemberService memberService;

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private RegionService regionService;
	/**
	 * 缓存
	 */
	@Autowired
	private Cache cache;

	public IPage<ExtensionVO> getExtensionPage(ExtensionVO extension, PageVO page) {
		QueryWrapper<Extension> queryWrapper = Wrappers.query();
		Member member = new Member();
		if (StringUtils.isNotEmpty(extension.getMemberId())) {
			member = memberMapper.selectById(extension.getMemberId());
		}
		if (StringUtils.isNotEmpty(extension.getExtension()) || StringUtils.isNotEmpty(member.getPromotionCode())) {
			// queryWrapper.eq("a.extension",
			// StringUtils.isNotEmpty(extension.getExtension()) ?
			// extension.getExtension() : member.getPromotionCode());
			queryWrapper.eq("a.extension",
					StringUtils.isNotEmpty(extension.getExtension())
							? extension.getExtension()
							: member.getPromotionCode());
		}
		if (StringUtils.isNotEmpty(extension.getType())) {
			// 1 用户 2 商家 3 天使 4 事业
			if ("1".equals(extension.getType())) {
				queryWrapper.eq("c.have_store", 0);
			} else if ("2".equals(extension.getType())) {
				queryWrapper.eq("c.have_store", 1);
			} else if ("3".equals(extension.getType())) {
				queryWrapper.eq("p.partner_type", 2);
			} else if ("4".equals(extension.getType())) {
				queryWrapper.eq("p.partner_type", 1);
			}
		}
		// queryWrapper.eq("p.delete_flag",0);
		// queryWrapper.eq("p.partner_state",0);
		queryWrapper.eq("a.delete_flag", 0);
		queryWrapper.gt("b.end_time", new Date());
		queryWrapper.groupBy("c.mobile ");
		return this.baseMapper.pageByMemberVO(PageUtil.initPage(page), queryWrapper);
	}

	@Override
	public IPage<ExtensionVO> getByPageCode(ExtensionVO extension, PageVO page) {
		QueryWrapper<Extension> queryWrapper = new QueryWrapper<>();
		Member member = new Member();
		if (StringUtils.isNotEmpty(extension.getMemberId())) {
			member = memberMapper.selectById(extension.getMemberId());
		}
		String id = UserContext.getCurrentUser().getId();
		QueryWrapper qu = new QueryWrapper();
		qu.eq("member_id", id);
		qu.eq("partner_state", 0);
		Partner partner = partnerMapper.selectOne(qu);
		List list = new ArrayList();
		if (StringUtils.isNotEmpty(partner.getRegionId())) {
			String regionId = partner.getRegionId();
			list = regionService.getPartnerAdCode(regionId, partner.getPartnerType().toString());
		}
		if ((StringUtils.isNotEmpty(extension.getExtension()) || StringUtils.isNotEmpty(member.getPromotionCode()))
				&& partner.getPartnerType() != 4) {
			queryWrapper.eq("a.extension",
					StringUtils.isNotEmpty(extension.getExtension())
							? extension.getExtension()
							: member.getPromotionCode());
		}
		if (StringUtils.isNotEmpty(extension.getType())) {
			// 1 用户 2 商家 3 天使 4 事业
			if ("1".equals(extension.getType())) {
				queryWrapper.eq("c.have_store", 0);
				queryWrapper.isNull("p.id");
			} else if ("2".equals(extension.getType())) {
				queryWrapper.eq("c.have_store", 1);
				queryWrapper.eq("p.audit_state", "PASS");
				queryWrapper.eq("p.pay_state", 1);
			} else if ("3".equals(extension.getType())) {
				queryWrapper.eq("p.partner_type", 2);
				queryWrapper.eq("c.have_store", 0);
				queryWrapper.eq("p.audit_state", "PASS");
				queryWrapper.eq("p.pay_state", 1);
			} else if ("4".equals(extension.getType())) {
				queryWrapper.eq("p.audit_state", "PASS");
				queryWrapper.eq("p.partner_type", 1);
				queryWrapper.eq("p.pay_state", 1);
			}
		}
		// queryWrapper.eq("p.delete_flag",0);
		// queryWrapper.eq("p.partner_state",0);
		if (partner.getPartnerType() == 4) {
			queryWrapper.in(list != null && list.size() > 0, "c.location", list);
			IPage<ExtensionVO> byPageMember = this.baseMapper.getByPageMember(PageUtil.initPage(page), queryWrapper);
			return byPageMember;
		}
		queryWrapper.eq("a.delete_flag", 0);
		IPage<ExtensionVO> byPageCode = this.baseMapper.getByPageCode(PageUtil.initPage(page), queryWrapper);
		return byPageCode;
	}

	/**
	 * @return
	 */
	public Boolean queryExtension(String promotionCode) {
		QueryWrapper<Member> queryWrapper = Wrappers.query();
		queryWrapper.eq("promotion_code", promotionCode);
		List<Member> memberList = memberMapper.selectList(queryWrapper);
		if (CollectionUtils.isNotEmpty(memberList)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Extension updateExtension(Extension extension) {
		// 判断是否用户登录并且会员ID为当前登录会员ID
		AuthUser tokenUser = UserContext.getCurrentUser();
		if (tokenUser == null) {
			throw new ServiceException(ResultCode.USER_NOT_LOGIN);
		}
		this.updateById(extension);
		return extension;
	}

	/**
	 * 添加推广管理
	 *
	 * @param extension
	 *            推广管理
	 * @return
	 */
	@Override
	public Extension addExtension(Extension extension) {
		this.save(extension);
		return extension;
	}

	@Override
	public boolean removeExtension(String id) {
		return this.remove(new QueryWrapper<Extension>().eq("id", id));
	}

	@Override
	public MemberVO findByMemberId(String memberId) {
		QueryWrapper<Extension> queryWrapper = Wrappers.query();
		queryWrapper.eq("e.member_id", memberId);
		queryWrapper.eq("e.delete_flag", 0);
		return this.baseMapper.findByMemberId(queryWrapper);
	}

	@Override
	public MemberVO findByPromotionCode(String promotionCode) {
		QueryWrapper<Extension> queryWrapper = Wrappers.query();
		queryWrapper.eq("m.promotion_code", promotionCode);
		queryWrapper.eq("m.delete_flag", 0);
		return this.baseMapper.findByPromotionCode(queryWrapper);
	}

	@Override
	public String getExtension() {
		String promotionCode = "";
		Set set = new HashSet();
		for (int i = 0; i < 1000000; i++) {
			set.add(generateInviteCode(6));
		}
		Iterator iterator = set.iterator();
		// 查询数据库中的推广码是否有重复的
		for (int i = 0; i < set.size(); i++) {
			String next = iterator.next() + "";
			Boolean s = queryExtension(next);// 查询是否有重复的推广码有则查询下一个是否有重复的
			if (!s) {
				promotionCode = next;
				return promotionCode;
			}
		}
		return promotionCode;
	}

	@Override
	public Boolean tempExToEx(String memberId, boolean isNull) {
		log.info("更新邀请 {}", "start");
		QueryWrapper<Extension> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		queryWrapper.eq("delete_flag", false);
		if (isNull) {
			queryWrapper.isNull("extension");
		}
		log.info("邀请对象 {},isNull", memberId, isNull);
		Extension extension = getOne(queryWrapper);
		log.info("邀请 {}", JSONUtil.toJsonStr(extension));
		Member member = memberMapper.selectById(memberId);
		if (member.getExtensionFlag() == null) {
			member.setExtensionFlag(Boolean.TRUE);
		}
		if (extension != null && member.getExtensionFlag()) {
			// 获取推广人身份
			MemberVO exMember = findByPromotionCode(extension.getTempExtension());

			if (!member.getHaveStore()) {
				// 用户
				// 如果是事业的推广码，则不进行绑定
				// 首次充值才能绑定
				List<Recharge> recharges = rechargeMapper.selectList(new QueryWrapper<Recharge>()
						.eq("member_id", memberId).eq("pay_status", "PAID").eq("recharge_way", "WECHAT"));
				List<Order> orders = orderMapper
						.selectList(new QueryWrapper<Order>().eq("member_id", memberId).eq("pay_status", "PAID"));
				if (!StrUtil.isBlankIfStr(recharges) && !StrUtil.isBlankIfStr(orders) && null != exMember
						&& !"事业合伙人".equals(exMember.getPartnerName())) {
					extension.setExtension(extension.getTempExtension());
					saveOrUpdate(extension);
					log.info("更新邀请码 {}", JSONUtil.toJsonStr(extension));
					member.setExtensionFlag(Boolean.FALSE);
					memberService.updateById(member);
				}
			} else {
				// 获取推广人身份
				if (StringUtils.isNotEmpty(extension.getExtension())) {
					MemberVO member0 = findByPromotionCode(extension.getExtension());
					// 如果推广人是天使，则剔除推广人
					if ("天使合伙人".equals(member0.getPartnerName())) {
						this.baseMapper.deleteById(extension.getId());
						log.info("剔除天使合伙人 {}", JSONUtil.toJsonStr(extension));
					}
				}
				if (null != exMember) {
					// 商家
					// 如果是事业的推广码，才绑定
					if ("事业合伙人".equals(exMember.getPartnerName())) {
						extension.setExtension(extension.getTempExtension());
						saveOrUpdate(extension);
						log.info("更新邀请码 {}", JSONUtil.toJsonStr(extension));
						member.setExtensionFlag(Boolean.FALSE);
						memberService.updateById(member);
					}
				}
			}
		} else {
			if (extension != null && member.getHaveStore() && StringUtils.isNotEmpty(extension.getExtension())) {
				MemberVO member0 = findByPromotionCode(extension.getExtension());
				// 如果推广人是天使，则剔除推广人
				if ("天使合伙人".equals(member0.getPartnerName())) {
					this.baseMapper.deleteById(extension.getId());
					log.info("剔除天使合伙人 {}", JSONUtil.toJsonStr(extension));
				}
			}
		}
		log.info("更新邀请 {}", "end");
		return true;
	}

	/**
	 * 绑定临时推广码
	 * 
	 * @param memberId
	 * @param exCode
	 * @return
	 */
	@Override
	public Boolean bindTempEx(String memberId, String exCode) {
		log.info("开始绑定tempEx memberId:{},exCode:{}", memberId, exCode);
		QueryWrapper<Extension> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		queryWrapper.eq("delete_flag", 0);
		Extension extension = getOne(queryWrapper);
		log.info("bindTempEx:{}", "Extension-" + JSONUtil.toJsonStr(extension));
		Member member = memberService.getById(memberId);
		if (member.getExtensionFlag() == null) {
			member.setExtensionFlag(Boolean.TRUE);
		}
		if (extension == null && member.getExtensionFlag()) {
			extension = new Extension();
			extension.setMemberId(memberId);
		}
		// if(StrUtil.isNotEmpty(exCode) && extension !=null && extension.getExtension()
		// == null &&
		// member.getExtensionFlag()){
		// extension.setTempExtension(exCode);
		//// extension.setExtension(exCode);
		// log.info("bindTempEx:{}",JSONUtil.toJsonStr(extension));
		// saveOrUpdate(extension);
		// return true;
		// }

		if (StrUtil.isNotEmpty(exCode) && extension != null && member.getExtensionFlag()
				&& extension.getExtension() == null) {
			// 获取推广人身份
			// MemberVO exMember = findByPromotionCode(extension.getTempExtension());
			MemberVO exMember = findByPromotionCode(exCode);
			if (exMember != null && "事业合伙人".equals(exMember.getPartnerName())) {
				extension.setTempExtension(exCode);
				saveOrUpdate(extension);
			}
			if (!member.getHaveStore()) {
				// 用户
				// 如果是事业的推广码，则不进行绑定
				// 首次充值才能绑定
				List<Recharge> recharges = rechargeMapper.selectList(new QueryWrapper<Recharge>()
						.eq("member_id", memberId).eq("pay_status", "PAID").eq("recharge_way", "WECHAT"));
				List<Order> orders = orderMapper
						.selectList(new QueryWrapper<Order>().eq("member_id", memberId).eq("pay_status", "PAID"));
				if (!StrUtil.isBlankIfStr(recharges) && !StrUtil.isBlankIfStr(orders) && null != exMember
						&& !"事业合伙人".equals(exMember.getPartnerName())) {
					extension.setExtension(exCode);
					saveOrUpdate(extension);
					log.info("更新邀请码 {}", JSONUtil.toJsonStr(extension));
					member.setExtensionFlag(Boolean.FALSE);
					memberService.updateById(member);
				}
			} else if (null != exMember) {
				// 商家
				// 如果是事业的推广码，才绑定
				if ("事业合伙人".equals(exMember.getPartnerName())) {
					extension.setExtension(extension.getTempExtension());
					saveOrUpdate(extension);
					log.info("更新邀请码 {}", JSONUtil.toJsonStr(extension));
					member.setExtensionFlag(Boolean.FALSE);
					memberService.updateById(member);
				}
			}
		}
		return false;

	}

	public Boolean bindEx(String memberId, String exCode) {
		log.info("开始绑定 memberId:{},exCode:{}", memberId, exCode);
		QueryWrapper<Extension> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("member_id", memberId);
		queryWrapper.eq("delete_flag", 0);
		queryWrapper.last("limit 1");
		Extension extension = getOne(queryWrapper);
		log.info("bindTempEx:{}", "Extension-" + JSONUtil.toJsonStr(extension));
		// 没有后续了，不知道要干嘛
		// if(extension==null){
		// extension=new Extension();
		// extension.setMemberId(memberId);
		// }
		if (StrUtil.isNotEmpty(exCode)) {
			if (StrUtil.isNotEmpty(extension.getTempExtension()) && StrUtil.isEmpty(extension.getExtension())) {
				extension.setExtension(exCode);
				log.info("bindTempEx:{}", JSONUtil.toJsonStr(extension));
				saveOrUpdate(extension);
				return true;
			}

		}
		return false;

	}

	@Override
	public List<Extension> getUnbindCount(String extension) {
		return this.baseMapper.getUnbindCount(extension);
	}

	@Override
	public List<Extension> updateUnbind(String extension) {
		return this.baseMapper.updateUnbind(extension);
	}

	@Override
	public PartnerVO getCertificate(String memberId) {
		return this.baseMapper.getCertificate(memberId);
	}

	@Override
	public boolean updateByExtensionCode(String extensionCode) {
		return this.baseMapper.updateByExtensionCode(extensionCode);
	}

	/**
	 * 生成邀请码方法
	 */
	public static String generateInviteCode(int len) {
		Assert.isTrue(len > 0, "长度要大于0");

		char[] chars = {'Q', 'W', 'E', '8', 'S', '2', 'D', 'Z', 'X', '9', 'C', '7', 'P', '5', 'K', '3', 'M', 'J', 'U',
				'F', 'R', '4', 'V', 'Y', 'T', 'N', '6', 'B', 'G', 'H', 'A', 'L'};
		Random random = new Random();
		char[] inviteChars = new char[len];
		for (int i = 0; i < len; i++) {
			inviteChars[i] = chars[random.nextInt(chars.length)];
		}
		return String.valueOf(inviteChars);
	}

	public Integer updateBymemberId(List<String> choseBindMemberIds) {
		Integer count = 0;
		for (String memberId : choseBindMemberIds) {
			boolean b = this.baseMapper.updateByMemberId(memberId);
			if (b) {
				count++;
			}
		}
		return count;
	}
}